<template>
  <el-dialog v-model="dialogVisible" :title="popTitle" width="600" :before-close="handleClose">
    <el-descriptions title="课程信息" border :column="1">
      <el-descriptions-item label="课程名称">
        {{info.curriculum_Info&&info.curriculum_Info.name}}</el-descriptions-item>
      <el-descriptions-item label="课程内容" v-if="info.approvalContent">
        <div>
          <div v-for="(item,index) in info.approvalContent.selectLesson" :key="index">{{index+1}}.{{item.name}}</div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="课程价格">{{proxy.$utils.formatNumber(info.price)}}</el-descriptions-item>
      <!-- 只有一次支付 -->
      <el-descriptions-item label="实际支付" v-if="info.pay_info && !info.signUpPrice">{{info.pay_info.pay_amount.total/100}}</el-descriptions-item>
      <!-- 有两次支付，这是第一次支付 -->
      <el-descriptions-item label="预付款" v-else-if="info.pay_info">
        <div class="flex alignCenter justifyBetween">
          <div class="flex alignCenter">
            <el-text class="mx-1" type="success" style="margin-right: 20px">{{proxy.$utils.formatNumber(info.pay_info.pay_amount.total/100)}}</el-text>
            <el-text type="primary">预付款余额:￥{{proxy.$utils.formatNumber(advancePayment)}}</el-text>
          </div>
          <el-checkbox v-model="checked1" size="large" :disabled="advancePayment==0" />
        </div>
      </el-descriptions-item>
      <!-- 尾款支付 -->
      <el-descriptions-item label="尾款支付" v-if="info.signUpPrice ">
        <div class="flex alignCenter justifyBetween">
          <div class="flex alignCenter">
            <el-text class="mx-1" v-if="info.balance_pay_info" style="margin-right: 20px" type="success">{{proxy.$utils.formatNumber(info.balance_pay_info.pay_amount.total/100)}}</el-text>
            <el-text class="mx-1" v-else style="margin-right: 20px" type="success">0</el-text>
            <el-text type="primary">尾款余额:￥{{proxy.$utils.formatNumber(balancePayment)}}</el-text>
          </div>
          <el-checkbox v-model="checked2" size="large" :disabled="balancePayment==0" />
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="支付总计">
        <el-text class="mx-1">{{proxy.$utils.formatNumber(info.payPrice)||0}}</el-text>
      </el-descriptions-item>
      <!-- 优惠减免金额 -->
      <el-descriptions-item label="优惠减免金额" v-if="discountAmount ">
        <div class="flex alignCenter justifyBetween">
          <el-text class="mx-1 errColor" type="danger">{{proxy.$utils.formatNumber(discountAmount)}}</el-text>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="订单金额">
        <el-text class="mx-1" type="primary">{{proxy.$utils.formatNumber(info.displayPrice)||0}}</el-text>
      </el-descriptions-item>
      <el-descriptions-item label="退款总计">
        <template #label>
          <div class="cell-item">退款总计</div>
        </template>
        {{refundAmount}}
      </el-descriptions-item>
      <el-descriptions-item label="退款理由">
        <el-input v-model="info.refundReason" :autosize="{ minRows:  4 }" type="textarea" placeholder="请输入退款理由" />
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading" :disabled="refundAmount==0&&info.hasOwnProperty('pay_info')">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();

let dialogVisible = ref(false);
let info = ref({});
let loading = ref(false);
const emit = defineEmits(["fatherMethod"]);
let checked1 = ref(false);
let checked2 = ref(false);
let popTitle = ref("");

let refundAmount = computed(() => {
  //退款总计
  let total = 0;
  if (checked1.value) total += advancePayment.value;
  if (checked2.value) total += balancePayment.value;
  return total;
});

//优惠减免金额
let discountAmount = computed(() => {
  if (!info.value.pay_discount_info) return 0;
  let arr = info.value.pay_discount_info || [];
  let amount = 0;
  arr.forEach((element) => {
    amount += element.info.amount.refund / 100;
  });
  return amount;
});

//预付款剩余
let advancePayment = computed(() => {
  let params = { ...info.value };
  if (!params.pay_info) return 0;
  let total = params.pay_info.pay_amount.total / 100;
  let amount = 0;
  let arr = params.pay_discount_info || [];
  arr.forEach((element) => {
    if (element.out_trade_no) {
      amount += element.info.amount.refund / 100;
    }
  });
  //如果有预付款退款，则减去预付款退款金额
  if (params.refund_info) {
    let newNum = total - params.refund_info.refund_amount.payer_refund / 100;
    total = newNum;
  }
  return total - amount;
});

//尾款余额
let balancePayment = computed(() => {
  let params = { ...info.value };
  if (!params.balance_pay_info) return 0;
  let total = params.balance_pay_info.pay_amount.total / 100;
  let arr = params.pay_discount_info || [];
  let amount = 0;
  arr.forEach((element) => {
    if (element.balance_out_trade_no) {
      amount += element.info.amount.refund / 100;
    }
  });
  //如果有尾款退款，则减去尾款退款金额
  if (params.balance_refund_info) {
    let newNum =
      total - params.balance_refund_info.refund_amount.payer_refund / 100;
    total = newNum;
  }
  return total - amount;
});

//一共支付的金额
let totalPaymentAmount = computed(() => {
  let params = { ...info.value };
  let total = 0;
  if (params.pay_info) {
    total += params.pay_info.pay_amount.total / 100;
  }
  if (params.balance_pay_info) {
    total += params.balance_pay_info.pay_amount.total / 100;
  }
  return total;
});

//订单可退款总计
let amountRefund = computed(() => {
  let params = { ...info.value };
  let arr = params.pay_discount_info || [];
  let amount = 0;
  arr.forEach((element) => {
    amount += element.info.amount.refund / 100;
  });
  return totalPaymentAmount.value - amount;
});

function selectLesson_format(e) {
  if (!e) return;
  let arr = [];
  e.forEach((element) => {
    arr.push(element.name);
  });
  return arr.toString();
}

async function open(row) {
  checked1.value = false;
  checked2.value = false;
  let resp = await proxy.$apis.orderAction({
    type: "details",
    data: { _id: row._id },
  });
  info.value = proxy.$utils.deepcopy(resp);
  popTitle.value = `退款 - ${row.approvalContent.model.name} - ${row.approvalContent.model.identityCard}`;
  console.log("订单详情", row);

  //预付款剩余
  if (advancePayment.value) checked1.value = true;
  //尾款剩余
  if (balancePayment.value) checked2.value = true;

  info.value.refundReason = "";
  dialogVisible.value = true;
}

function handleClose() {
  checked2.value = false;
  checked1.value = false;
  emit("fatherMethod");
  info.value = {};
  dialogVisible.value = false;
}

function submit() {
  //免费的单子
  if (info.value.price == 0 && !info.value.hasOwnProperty("pay_info")) {
    free();
  } else if (discountAmount.value) {
    send();
  } else {
    save();
  }
}

async function free() {
  try {
    loading.value = true;
    if (!info.value.refundReason)
      return proxy.$utils.showToast("请输入退款理由", 0);
    let data = {
      orderId: info.value._id,
      status: 4,
      refund_info: {
        refundReason: info.value.refundReason,
        updateUser: counter.updateUser,
        refund_time: new Date(),
      },
    };
    await proxy.$apis.orderAction({ type: "freeOrderRefund", data });
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

//有支付优惠的情况
async function send() {
  try {
    loading.value = true;
    let obj = {
      orderId: info.value._id,
      payType: info.value.payType,
      updateUser: counter.updateUser,
      refundReason: info.value.refundReason,
      changeOrderStatus: 1, //退款完修改订单状态
    };
    console.log("尾款余额", balancePayment.value);
    if (checked2.value) {
      let query = {
        key: "balance_out_trade_no",
        out_trade_no: info.value.balance_out_trade_no,
        total: info.value.balance_pay_info.pay_amount.total,
        refund: balancePayment.value * 100,
      };
      //return console.log("queryquerychecked2", { ...obj, ...query });
      await proxy.$apis.orderRefund({ ...obj, ...query });
    }
    if (checked1.value) {
      let query = {
        key: "out_trade_no",
        out_trade_no: info.value.out_trade_no,
        total: info.value.pay_info.pay_amount.total,
        refund: advancePayment.value * 100,
      };
      //return console.log("queryquerychecked1", { ...obj, ...query });
      await proxy.$apis.orderRefund({ ...obj, ...query });
    }
    proxy.$utils.showToast("退款成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

//没有支付优惠的情况
async function save() {
  try {
    loading.value = true;

    if (!info.value.refundReason)
      return proxy.$utils.showToast("请输入退款理由", 0);

    if (!refundAmount.value) return proxy.$utils.showToast("请选择退款金额", 0);

    let obj = {
      payType: info.value.payType,
      updateUser: counter.updateUser,
      refundReason: info.value.refundReason,
    };

    //如果有尾款支付，则需要单独退款
    if (info.value["balance_pay_info"]) {
      if (checked1.value) {
        obj["out_trade_no"] = info.value.out_trade_no;
        obj["amount"] = info.value.pay_info.pay_amount.total;
      }
      if (checked2.value) {
        obj["balance_out_trade_no"] = info.value.balance_out_trade_no;
        obj["balance_amount"] = info.value.balance_pay_info.pay_amount.total;
      }
    } else {
      obj["out_trade_no"] = info.value.out_trade_no;
      obj["amount"] = info.value.pay_info.pay_amount.total;
    }
    //return console.log("objobj", obj);
    await proxy.$apis.orderRefund(obj);
    proxy.$utils.showToast("退款成功");
    handleClose();
  } catch (error) {
    console.log("退款失败", error);
  } finally {
    loading.value = false;
  }
}

defineExpose({ open });
</script>



<style lang="scss" scoped>
.cell-item {
  color: #f89f66;
  width: 100px;
}
.mx-1 {
  font-weight: bold;
}
</style>



